/**
 * 
 */
package org.swing.utility.jdbc.backend;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lqnhu
 *
 */
public class SimpleObjectListConverter implements Store.Converter {
	private final Class componentClass;

	public SimpleObjectListConverter(Class componentClass) {
		this.componentClass = componentClass;
	}

	public Object intern(Object store, String val) throws Exception {
		ArrayList<Object> out = new ArrayList<Object>();
		int curPos = 0;
		while (true) {
			int nextNL = val.indexOf('\n', curPos);
			if (nextNL < 0)
				break;
			String id = val.substring(curPos, nextNL);
			curPos = nextNL + 1;
			out.add(id.isEmpty() ? null : Store.intern(store, componentClass,
					id));
		}
		// make sure that there is no left-over junk
		if (curPos != val.length())
			throw new Exception("list must be empty or end in a newline");
		return out;
	}

	public String extern(Object store, Object val) throws Exception {
		StringBuffer out = new StringBuffer();
		for (Object comp : (List<Object>) val)
			out.append(comp == null ? "" : Store.extern(store, comp)).append(
					'\n');
		return out.toString();
	}
}
